package com.keqing.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.ganyu.domain.ResponseResult;
import com.ganyu.domain.dto.AddCategoryDto;
import com.ganyu.domain.dto.UpdateCategoryDto;
import com.ganyu.domain.entity.Category;
import com.ganyu.domain.vo.ExcelCategoryVo;
import com.ganyu.enums.AppHttpCodeEnum;
import com.ganyu.service.impl.CategoryServiceImpl;
import com.ganyu.utils.BeanCopyUtils;
import com.ganyu.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.ganyu.enums.AppHttpCodeEnum.CAN_NOT_WATCH;

/**
 * DATA: 2022/9/29
 * Author: 晨夕
 */
@RestController
@RequestMapping("/content/category")
public class CateGoryController {

    @Autowired
    private CategoryServiceImpl categoryServiceImpl;

    @GetMapping("/listAllCategory")
    public ResponseResult getCategoryList(){
        return categoryServiceImpl.getCategoryList();
    }


    @PreAuthorize("@ps.hasPermission()")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryServiceImpl.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(CAN_NOT_WATCH);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

    @GetMapping("/list")
    public ResponseResult selectList(Integer pageNum,Integer pageSize,String name,String status){
        return categoryServiceImpl.selectList(pageNum, pageSize, name, status);
    }

    @PreAuthorize("@ps.hasPermission()")
    @PostMapping
    public ResponseResult addList(@RequestBody AddCategoryDto addCategoryDto){
        return categoryServiceImpl.addList(addCategoryDto);
    }

    @GetMapping("/{id}")
    public ResponseResult selectById(@PathVariable("id") Long id){
        return categoryServiceImpl.selectById(id);
    }

    @PreAuthorize("@ps.hasPermission()")
    @PutMapping
    public ResponseResult updateCagegory(@RequestBody UpdateCategoryDto updateCategoryDto){
        return categoryServiceImpl.updateCagegory(updateCategoryDto);
    }

    @PreAuthorize("@ps.hasPermission()")
    @DeleteMapping("/{id}")
    public ResponseResult deleteCagegory(@PathVariable("id") Long[] ids){
        return categoryServiceImpl.deleteCagegory(ids);
    }
}
